/*
 * Copyright (c) 2009-2011, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/directx9/DirectXRenderTarget.h"
#include "alkes/directx9/DirectXGraphics.h"
#include "alkes/directx9/DirectXVertexBuffer.h"
#include "alkes/directx9/DirectXImageBuffer.h"


namespace alkes {

DirectXRenderTarget* DirectXRenderTarget::createBackSurface(DirectXGraphics& directx)
{
    TargetBehavior target_behavior;
    {
        const D3DPRESENT_PARAMETERS& pre_param = directx.getPresentParameters();
        switch (pre_param.SwapEffect)
        {
        case D3DSWAPEFFECT_DISCARD:
            target_behavior = AL_BEHAVIOR_DISCARD;
            break;
        case D3DSWAPEFFECT_COPY:
            /* TODO: Research copy behavior.
            the content of the back buffer is changed in some environment.
            */
            //target_behavior = AL_BEHAVIOR_SINGLE;
            target_behavior = AL_BEHAVIOR_DISCARD;
            break;
        case D3DSWAPEFFECT_FLIP:
            if (pre_param.BackBufferCount == 1)
                target_behavior = AL_BEHAVIOR_DOUBLE;
            else if (pre_param.BackBufferCount == 2)
                target_behavior = AL_BEHAVIOR_TRIPLE;
            else
                return 0;
            break;
        default:
            return 0;
        }
    }

    URect rect(0, 0,
        (Rect::value_type)directx.getPresentParameters().BackBufferWidth,
        (Rect::value_type)directx.getPresentParameters().BackBufferHeight);
    DirectXRenderTarget* target = new DirectXRenderTarget(directx, rect, target_behavior);

    return target;
}

void DirectXRenderTarget::destroy()
{
    delete this;
}

DirectXRenderTarget::DirectXRenderTarget(DirectXGraphics& directx, const Rect& rect, TargetBehavior target_behavior)
: IRenderTarget3D(&directx, target_behavior)
, render_target_(0)
, rect_(rect)
{
}

DirectXRenderTarget::DirectXRenderTarget(DirectXGraphics& directx, IDirect3DSurface* target, TargetBehavior target_behavior)
: IRenderTarget3D(&directx, target_behavior)
, render_target_(target)
{
    if (target)
    {
        D3DSURFACE_DESC desc;
        target->GetDesc(&desc);
        rect_.x = 0;
        rect_.y = 0;
        rect_.width = (Rect::value_type)desc.Width;
        rect_.height = (Rect::value_type)desc.Height;
    }
}

DirectXRenderTarget::~DirectXRenderTarget()
{
    releaseSurface();
}

void DirectXRenderTarget::releaseSurface()
{
    if (render_target_)
    {
        render_target_->Release();
        render_target_ = 0;
    }
}

void DirectXRenderTarget::setSurface(IDirect3DSurface* new_surface)
{
    releaseSurface();
    render_target_ = new_surface;
}

void DirectXRenderTarget::onSnapshot(ImageWriter& writer, const Rect& rect)
{
    IDirect3DSurface* surface = render_target_;

    PixelFormat format;
    {
        D3DSURFACE_DESC desc;
        if (!FAILED(surface->GetDesc(&desc))
            || AL_PIXEL_FORMAT_UNKNOWN == (format = dxformat2alformat(desc.Format)))
        {
            AL_ASSERT(false);
            surface->Release();
            return ;
        }
    }

    D3DLOCKED_RECT locked;
    RECT lock_rect;
    lock_rect.left = rect.x;
    lock_rect.top = rect.y;
    lock_rect.right = rect.x + rect.width;
    lock_rect.bottom = rect.y + rect.height;

    if (!FAILED(surface->LockRect(&locked, &lock_rect, D3DLOCK_READONLY)))
    {
        writer.write(format, locked.pBits, locked.Pitch, rect.width, rect.height);
        surface->UnlockRect();
    }

    surface->Release();
}

DirectXGraphics* DirectXRenderTarget::getDirectXGraphics() const
{
    return static_cast<DirectXGraphics*>(getIGraphics3D());
}

void DirectXRenderTarget::onResetDevice()
{
}

void DirectXRenderTarget::beginDraw3D()
{
    getDirectXGraphics()->beginDraw3D();
}

void DirectXRenderTarget::endDraw3D()
{
    getDirectXGraphics()->endDraw3D();
}

void DirectXRenderTarget::beginDraw2D()
{
    getDirectXGraphics()->beginDraw2D();
}

void DirectXRenderTarget::endDraw2D()
{
    getDirectXGraphics()->endDraw2D();
}

const Rect DirectXRenderTarget::getTargetRect() const
{
    return rect_;
}

void DirectXRenderTarget::setViewport(const Viewport& viewport)
{
    getDirectXGraphics()->setViewport(viewport);
}

const Viewport DirectXRenderTarget::getViewport() const
{
    return getDirectXGraphics()->getViewport();
}

void DirectXRenderTarget::setPerspective(float angle, float aspect, float znear, float zfar)
{
    getDirectXGraphics()->setPerspective(angle, aspect, znear, zfar);
}

void DirectXRenderTarget::setLookAt(const Vector3D& eye, const Vector3D& at, const Vector3D& up)
{
    getDirectXGraphics()->setLookAt(eye, at, up);
}

void DirectXRenderTarget::translate(float x, float y, float z)
{
    getDirectXGraphics()->translate(x, y, z);
}

void DirectXRenderTarget::scale(float xscale, float yscale, float zscale)
{
    getDirectXGraphics()->scale(xscale, yscale, zscale);
}

void DirectXRenderTarget::rotate(float angle, float x, float y, float z)
{
    getDirectXGraphics()->rotate(angle, x, y, z);
}

void DirectXRenderTarget::setScissorRect(const Rect& rect)
{
    getDirectXGraphics()->setScissorRect(rect);
}

const Rect DirectXRenderTarget::getScissorRect()
{
    return getDirectXGraphics()->getScissorRect();
}

void DirectXRenderTarget::setState(int state, bool enable)
{
    getDirectXGraphics()->setState(state, enable);
}

bool DirectXRenderTarget::getState(int state)
{
    return getDirectXGraphics()->getState(state);
}

void DirectXRenderTarget::setAlphaBlendMode(AlphaBlendMode src_blend, AlphaBlendMode dst_blend)
{
    getDirectXGraphics()->setAlphaBlendMode(src_blend, dst_blend);
}

void DirectXRenderTarget::getAlphaBlendMode(AlphaBlendMode* src_blend, AlphaBlendMode* dst_blend)
{
    getDirectXGraphics()->getAlphaBlendMode(src_blend, dst_blend);
}

void DirectXRenderTarget::clearBuffer(uint32_t buffer_flag, const Color& clear_color, const Rect* rect, float depth)
{
    getDirectXGraphics()->clearBuffer(buffer_flag, clear_color, rect, depth);
}

bool DirectXRenderTarget::drawPrimitive(IVertexBuffer* vbuffer, PrimitiveType type, uint32_t start, uint32_t count)
{
    return getDirectXGraphics()->drawPrimitive(vbuffer, type, start, count);
}

bool DirectXRenderTarget::setTexture(Image* image, int stage)
{
    AL_PRE_COND(0 <= stage, false);

    DirectXImageBuffer* texture = 0;

    if (image)
    {
        texture = restrict_cast<DirectXImageBuffer*>(image->getImageBuffer());
    }

    getDirectXGraphics()->setTexture(stage, texture);

    return true;
}

void DirectXRenderTarget::setTextureFilter(TexFilterValue min_filter, TexFilterValue mag_filter, int stage)
{
    getDirectXGraphics()->setTextureFilter(min_filter, mag_filter, stage);
}

void DirectXRenderTarget::getTextureFilter(TexFilterValue* min_filter, TexFilterValue* mag_filter, int stage)
{
    getDirectXGraphics()->getTextureFilter(min_filter, mag_filter, stage);
}

void DirectXRenderTarget::setTextureAddressMode(TexAddressMode u_mode, TexAddressMode v_mode, int stage)
{
    getDirectXGraphics()->setTextureAddressMode(u_mode, v_mode, stage);
}

void DirectXRenderTarget::getTextureAddressMode(TexAddressMode* u_mode, TexAddressMode* v_mode, int stage)
{
    getDirectXGraphics()->getTextureAddressMode(u_mode, v_mode, stage);
}

void DirectXRenderTarget::pushMatrix()
{
    getDirectXGraphics()->pushMatrix();
}

void DirectXRenderTarget::popMatrix()
{
    getDirectXGraphics()->popMatrix();
}

void DirectXRenderTarget::translate(float x, float y)
{
    getDirectXGraphics()->translate(x, y);
}

void DirectXRenderTarget::translateForImage(float x, float y)
{
    getDirectXGraphics()->translate(x - 0.5f, y - 0.5f);
}

void DirectXRenderTarget::scale(float xscale, float yscale, const Vector2D& origin)
{
    getDirectXGraphics()->scale(xscale, yscale, origin);
}

void DirectXRenderTarget::rotate(float degrees, const Vector2D& origin)
{
    getDirectXGraphics()->rotate(degrees, origin);
}

void DirectXRenderTarget::skewX(float angle)
{
    getDirectXGraphics()->skewX(angle);
}

void DirectXRenderTarget::skewY(float angle)
{
    getDirectXGraphics()->skewY(angle);
}

}
